import { updateUserInfo, saveFile } from '../../../api/index'
const uploadOss = require('../../../utils/upload/uploadImg.js')

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },
  data: {
    value: ''
  },
  methods: {
    uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
      return new Promise((resolve, reject) => {
        uploadOss(item[key],
          (res) => {
            resolve(res)
          },
          (err) => {
            resolve()
          },
          files, index, that, dataKey
        )
      })
    },
    async getUserProfile () {
      try {
        const { userInfo } = await wx.$pro.getUserProfile({ desc: '用于完善会员资料' })
        const { path: headImage } = await wx.$pro.getImageInfo({ src: userInfo.avatarUrl })
        let files = [{ tempFilePath: headImage }]
        const { fileUrl } = await this.uploadFile(files[0], 'tempFilePath')
        const { ResultSet } = await saveFile({ fileList: [{ fileUrl: fileUrl }] })
        let query = { ...userInfo, headImage: ResultSet.userData.fileIdList[0].fileId, authorize: true }
        let filters = ['headImage', 'nickName', 'gender', 'mail', 'birth', 'city', 'province', 'area']
        filters.forEach(key => {
          if (!query[key]) delete query[key]
        })
        await updateUserInfo({ ...query })
        this.triggerEvent('update')
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    close () {
      this.triggerEvent('close')
    }
  }
})